package main

import (
	"context"
	"crypto/sha512"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"google.golang.org/grpc"
	"mxshop_srvs/user_srv/proto"
)

// 测试user的grpc服务
var userClient proto.UserClient
var conn *grpc.ClientConn

func Init() {
	var err error
	conn, err = grpc.Dial("127.0.0.1:50051", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	userClient = proto.NewUserClient(conn)
}

/*
*
测试获取用户列表的服务
*/
func TestGetUserList() {
	rsp, err := userClient.GetUserList(context.Background(), &proto.PageInfo{
		Pn:    1,
		PSize: 10,
	})
	if err != nil {
		panic(err)
	}
	for _, user := range rsp.Data {
		fmt.Println(user.Id, user.Mobile, user.NickName)
	}
}

// 根据id获取用户
func TestGetUserById() {
	rsp, err := userClient.GetUserById(context.Background(), &proto.IdRequest{
		Id: 2,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp)
	EncodedPassWord := rsp.PassWord

	//校验密码是不是123456
	resp, err := userClient.CheckPassWord(context.Background(), &proto.PasswordCheckInfo{
		Password:          "123456",
		EncryptedPassword: EncodedPassWord,
	})
	if resp.Success {
		fmt.Println("密码正确")
		return
	}
	fmt.Println("密码验证错误")
}

// 根据mobile获取用户
func TestGetUserByMobile() {
	rsp, err := userClient.GetUserByMobile(context.Background(), &proto.MobileRequest{
		Mobile: "18533450978",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp)
}

// 测试创建用户
func TestCreateUser() {
	rsp, err := userClient.CreateUser(context.Background(), &proto.CreateUserInfo{
		NickName: "张三",
		PassWord: "123456",
		Mobile:   "18533450978",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp.NickName, rsp.Mobile)
}

// 修改用户
func TestUpdateUser() {
	rsp, err := userClient.UpdateUser(context.Background(), &proto.UpdateUserInfo{
		Id:       2,
		NickName: "xxx",
		Gender:   "female",
		BirthDay: 972134568, //传一个s为单位的时间戳
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp)
}

//校验用户密码是否正确

// 批量生产10个用户
func BatchCreateUser() {
	options := &password.Options{16, 100, 32, sha512.New}
	salt, encodedPwd := password.Encode("123456", options)
	newPassword := fmt.Sprintf("$pbkdf2-sha512$%s$%s", salt, encodedPwd)

	for i := 0; i < 10; i++ {
		rsp, err := userClient.CreateUser(context.Background(), &proto.CreateUserInfo{
			NickName: fmt.Sprintf("bobby%d", i),
			Mobile:   fmt.Sprintf("1991111000%d", i),
			PassWord: newPassword,
		})
		if err != nil {
			panic(err)
		}
		fmt.Println(rsp.NickName, rsp.Mobile)
	}
}

func main() {
	Init()
	//TestGetUserList()
	//TestCreateUser()
	//TestGetUserById()
	//TestUpdateUser()
	BatchCreateUser()
	conn.Close()
}
